<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_News extends Controller_ClientTemplate
{
    
    public function action_index()
    {       
        $name = Request::$current->param('name', '');
        if( $name == ''){
            $this->auto_render = true;
             
            $news_view = View::factory('news/news')
                            ->bind('news', $news)
                            ->bind('page_links', $page_links);
                                           
          
            $count = DB::select(DB::expr('COUNT(*) AS `count`'))->from('news')->execute()->get('count');
                    
            $pagination = Pagination::factory(array(
                    'total_items'    => $count,
                    'items_per_page' => 10,
            ));
                    
            $news = DB::select()->from('news')
                            ->order_by('created','DESC')
                            ->limit($pagination->items_per_page)
                            ->offset($pagination->offset)->as_object()->execute();
                 
            $page_links = $pagination->render();
            
            $this->template->title = "Новости";
            $this->template->content = $news_view->render();
            
        } else {
            $this->auto_render = true;
            
            $result = DB::query(Database::SELECT, "SELECT *
                                                   FROM `news`
                                                   WHERE `name`=:name
                                                   LIMIT 1")
                        ->param(':name', $name)
                        ->as_object()
                        ->execute()
                        ->current();
                        
            if($result){
                $this->template->title = $result->html_title;
                $this->template->description = $result->html_description;
                $this->template->keywords = $result->html_keyword;
                $this->template->content = $result->content;                
            }
        }
    }
    
    public function action_block()
    {
        $this->auto_render = false;
        
        $block = View::factory('news/block')
                        ->bind('news', $news);
        
        $news = DB::query(Database::SELECT, "SELECT `name`, `html_title`,`content`, `created`
                            FROM `news`
                            ORDER BY `created` DESC
                            LIMIT 3")
                    ->as_object()
                    ->execute();                
        
        Request::$current->response()->body($block->render());
        
    }

}